﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

/// <summary>
/// Unity 功能组件
/// </summary>
public static class UnityUtil
{



    public static T GetOrAddComponent<T>(this GameObject obj) where T : Component
    {
        if (obj == null)
            return null;

        T t = obj.GetComponent<T>();
        if (t == null)
        {
            t = obj.AddComponent<T>();
        }
        return t;
    }

    public static T GetOrAddCompument<T>(this GameObject obj) where T : Component
    {
        T t = GetOrAddComponent<T>(obj);
        return t;
    }

    public static T GetOrAddComponent<T>(this GameObject obj, Type type2) where T : Component
    {
        if (obj == null)
            return null;
        Component t = obj.GetComponent(type2);
        if (t == null)
        {
            t = obj.AddComponent(type2);
        }
        return t as T;
    }

    public static void DestroyT<T>(this GameObject obj) where T : Component
    {
        if (obj == null) return;
        if (obj.GetComponent<T>())
        {
            GameObject.Destroy(obj.GetComponent<T>());
        }
    }


    public static void ClearListT<T>(this List<T> list, int userCount = 0) where T : Component
    {
        if (list == null) return;
        if (list.Count > userCount)
        {
            for (int i = userCount; i < list.Count; i++)
            {
                GameObject.Destroy(list[i].gameObject);
            }
        }

        list.Clear();
    }

    public static void HideUnUserT<T>(this List<T> list, int userCount = 0) where T : Component
    {
        if (list.Count > userCount)
        {
            for (int i = userCount; i < list.Count; i++)
            {
                list[i].gameObject.SetActive(false);
            }
        }
    }




    public static T GetOrCreateT<T>(this List<T> list, ref int userCount, GameObject CampPanelPrefb = null, Transform parent = null) where T : Component
    {
        userCount++;
        T chart = null;
        if (list.Count < userCount)
        {
            if (CampPanelPrefb == null)
            {
                chart = GetOrAddComponent<T>(new GameObject());
            }
            else
            {
                chart = GameObject.Instantiate(CampPanelPrefb).GetOrAddComponent<T>();
            }
            chart.transform.SetParent(parent);
            chart.gameObject.SetActive(true);

            chart.transform.localRotation = Quaternion.identity;
            chart.transform.localScale = Vector3.one;

            Vector3 v3 = chart.transform.localPosition;
            v3.z = 0;
            chart.transform.localPosition = v3;
            list.Add(chart);
        }
        else
        {
            chart = list[userCount - 1];
            list[userCount - 1].gameObject.SetActive(true);
        }
        return chart;
    }


    /// <summary>
    /// 下载资源
    /// </summary> 
    public static IEnumerator DownloadData(string dataUrl, Action<WWW> OnCompleteDownload, int DownloadTimeOut = 5)
    {
        WWW www = new WWW(dataUrl);
        float timeOut = Time.time;
        float progress = 0;
        while (www != null && !www.isDone)
        {
            if (progress < www.progress)
            {
                timeOut = Time.time;
                progress = www.progress;
            }
            if (Time.time - timeOut > DownloadTimeOut)
            {
                Debug.Log("超时下载！");
                if (OnCompleteDownload != null)
                    OnCompleteDownload(null);
                yield break;
            }
            yield return null;//等一帧 避免卡死
        }
        yield return www;

        if (www != null && string.IsNullOrEmpty(www.error))
        {
            string concent = www.text;
            concent = System.Text.Encoding.UTF8.GetString(www.bytes);

            if (OnCompleteDownload != null)
                OnCompleteDownload(www);
            Debug.Log("数据下载完成！");
            yield break;
        }
        else
        {
            Debug.Log("下载失败！" + www.error);
            if (OnCompleteDownload != null)
                OnCompleteDownload(null);
            yield break;
        }
    }

    //public static System.Runtime.CompilerServices.TaskAwaiter GetTaskAwaiter(this UnityEngine.Networking.UnityWebRequestAsyncOperation web)
    //{
    //    var tcs = new System.Runtime.CompilerServices<object>();

    //    web.completed += obj => { tcs.TrySetResult(null); };
    //    return (tcs.Task).GetAwaiter();
    //}




    public static string ConverJsonSerializer(this string str)
    {
        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
        System.IO.TextReader tr = new System.IO.StringReader(str);
        Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(tr);
        object obj = serializer.Deserialize(jtr);
        if (obj != null)
        {
            StringWriter textWriter = new StringWriter();
            Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(textWriter)
            {
                Formatting = Newtonsoft.Json.Formatting.Indented,
                Indentation = 4,
                IndentChar = ' '
            };
            serializer.Serialize(jsonWriter, obj);
            return textWriter.ToString();
        }
        else
        {
            return str;
        }
    }

}
